<?php


namespace app\api\controller;


use app\BaseController;

use app\middleware\coupon_order\CheckAgentJutuikeChannelPremission;
use app\model\AgentChannel;
use app\model\CouponBrand;
use app\model\CouponCate;
use app\model\PageSetting;
use think\Request;
use app\common\service\supplier\JumpTypeService;


class Coupon extends BaseController
{

    //主聚推客

    use \app\api\controller\traits\coupon_order\Jutuike;//聚推客渠道接口整理


    protected $middleware = [
        \app\middleware\ApiChannel::class,
        \app\middleware\ApiUserAuthV2::class => ['except' => ['phoneInfo']],
        \app\middleware\coupon_order\CheckAgentJutuikeChannelPremission::class => ['only' => [ //聚推客
            'getUnionUrl',
            'getFoodJumpUrl',
            'getJumpUrlByTravelId',
            'getJumpUrlByBrandId',//权益
        ]],
    ];

    protected function initialize()
    {

        $supplierChannle = CheckAgentJutuikeChannelPremission::matchChannel();

        $this->request->servType = $supplierChannle ? $supplierChannle->supplierInfo->serv_type : PRODUCT_COUPON_SERV;

        $this->request->servName = '渠道';

        parent::initialize();
    }

    /**
     * 获取分类和品牌信息
     */
    public function getCateAndSubBrand()
    {
        //todo 都要有值才显示最顶级的分类

//        $data = CouponCate::query()->where('coupon_cate.status', CouponCate::STATUS_ACTIVE)
//            ->with(['couponBrand' => function($query){
//                //todo 无效，后面查看源码
//                $query->where('coupon_brand.status', CouponBrand::STATUS_ACTIVE);
//            }])
//            ->field(['c.*'])
//            ->alias('c')
//            ->join('coupon_brand_cate_relation r', 'c.id = r.cate_id')
//            ->join('coupon_brand b', 'b.id = r.brand_id')
//            ->join('coupon_product p', 'b.id = p.brand_id')
//            ->join('coupon_product_channel ch', 'p.id = ch.product_id')
//            ->where('c.status', CouponCate::STATUS_ACTIVE)
//            ->where('b.status', CouponBrand::STATUS_ACTIVE)
//            ->where('p.status', CouponProduct::STATUS_ACTIVE)
//            ->where('ch.status', CouponProductChannel::STATUS_ACTIVE)
//            ->group('coupon_cate.id')
//            ->order('c.sort desc')
//            ->select();


        $datas = CouponCate::query()
            ->where('status', CouponCate::STATUS_ACTIVE)
            ->order('sort desc, updated_at desc')
            ->select()->toArray();

        foreach ($datas as $key => &$data) {
            $data['couponBrand'] = [];
            //过滤掉新权益上线前的品牌
            $dateTime = '2022-07-18';
            $brands = CouponBrand::hasWhere('product')
                ->join('coupon_brand_cate_relation', 'coupon_brand_cate_relation.brand_id = coupon_brand.id')
                ->where('coupon_brand_cate_relation.cate_id', $data['id'])
                ->where('coupon_brand.status', CouponBrand::STATUS_ACTIVE)
                ->where('coupon_brand.created_at', '<', date('Y-m-d H:i:s',strtotime($dateTime)))
                ->order('coupon_brand.sort desc, coupon_brand.updated_at desc')
                ->select()->toArray();

            /**
             * @var AgentChannel $agentChannel
             */
            $agentChannel = $this->request->agentChannel;
            $couponBrand = new CouponBrand();
            $travelUnion = $couponBrand->getJutuikelList([
                'type' => CouponBrand::TYPE_TRAVEL,
                'status' => CouponBrand::STATUS_ACTIVE,
                'field' => 'act_id, name, act_name, image_url, type'
            ])->toArray();
            $foodUnion = $couponBrand->getJutuikelList([
                'type' => $couponBrand::TYPE_UNION_FOOD,
                'status' => $couponBrand::STATUS_ACTIVE,
                'field' => 'act_id, name, act_name, image_url, type'
            ])->toArray();
            $diyModules = [
                [
                    'name' => '日常出行',
                    //'const' => TravelUnion::TRAVELSTATICDATA,
                    'const' => $travelUnion,
                    'serv_type' => PRODUCT_TRAVEL_OIL_SERV,
                ],
                [
                    'name' => '餐饮美食',
                   // 'const' => FoodUnion::PRODUCTS,
                    'const' => $foodUnion,
                    'serv_type' => PRODUCT_FOOD_SHOP_SERV,
                ]
            ];

            foreach ($diyModules as $diyModule) {

                $hasType = $agentChannel->hasServType($diyModule['serv_type']); //判断是否有出行的权限
                if ($data['name'] == $diyModule['name'] && $hasType) {
                    $brands = $brands ? $brands : [];
                    $brands_temp = $diyModule['const'];
                    if ($brands) {
                        foreach ($brands as $brand) {
                            array_push($brands_temp, $brand);
                        }
                    }
                    $brands = $brands_temp;
                }
            }

            //判断渠道是否配置出行
            if (count($brands) != 0) {
                $data['couponBrand'] = $brands;
            } else {
                unset($datas[$key]);
            }
        }

        return success('', array_values($datas));

    }

    /**
     * 顶部推荐
     */
    public function getTop(Request $request)
    {
        //临时方案
        //有id 跳聚推客，没有id 跳自己的
        $rows = [
            [
                'name' => '腾讯',
                'image_url' => 'https://img.jutuike.com/taokeout/mall/icon/qqv.png',
                'brand_id' => '2',
                'id' => '2',
            ],
            [
                'name' => '优酷',
                'image_url' => 'https://img.jutuike.com/taokeout/mall/icon/youku.png',
                'brand_id' => '3',
                'id' => '3',
            ],
            [
                'name' => '爱奇艺',
                'image_url' => 'https://img.jutuike.com/taokeout/mall/icon/iqiyi.png',
                'brand_id' => '1',
                'id' => '1',
            ],
            [
                'name' => '喜马拉雅',
                'image_url' => 'https://img.jutuike.com/taokeout/mall/icon/ximalaya.png',
                'brand_id' => '5',
                'id' => '5',
            ],
            [
                'name' => 'QQ音乐',
                'image_url' => 'https://img.jutuike.com/taokeout/mall/icon/qqyinyue.png',
                'brand_id' => '20',
                'id' => '20',
            ]
        ];
        //add by ymzhang 2022-07-04
        foreach ($rows as $key => $brand) {
            $info = CouponBrand::find($brand['brand_id']);
            $rows[$key]['discount_logo'] = $info->discount_logo;
            $rows[$key]['subtitle'] = $info->subtitle;
        }

        $ad_banner = [
            [
                'name' => '饿了么',
                'brand_id' => '7',
                'id' => '7',
            ]
        ];

        $ad_block = [
            [
                'name' => 'QQ音乐',
                'image_url' => 'https://img.jutuike.com/taokeout/mall/icon/qqyinyue.png',
                'brand_id' => '20',
                'id' => '20',
            ],
            [
                'name' => '饿了么',
                'brand_id' => '7',
                'id' => '7',
                'image_url' => 'https://img.jutuike.com/taokeout/mall/icon/ele.png',
            ],
            [
                'name' => '美团',
                'brand_id' => '6',
                'id' => '6',
                'image_url' => 'https://img.jutuike.com/taokeout/mall/icon/meituan.png',
            ]
        ];


        return success('成功！', compact('rows', 'ad_banner', 'ad_block'));
    }


    /**
     * @note 顶部推荐new
     * @access public
     * @method get
     * @author ymzhang
     * @date 2022-09-01
     * @time 17:45
     * @returns
     */
    public function getJumpConfig(Request $request)
    {
        $params = $request->param();
        if ($params['type'] != PageSetting::TYPE_COUPON) {
            return fail('类型参数错误');
        }
        return (new JumpTypeService())->getJumpConfig($params);
    }



}